﻿using System;
using System.ComponentModel;
using System.Globalization;
using HSS.Resources;

namespace HSS.ComponentModel
{
	public class BooleanConverter : TypeConverter
	{
		public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
		{
			return ((sourceType == typeof(string)) || base.CanConvertFrom(context, sourceType));
		}

		public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
		{
			var str = value as string;
			if (null != str)
			{
				str = str.Trim();
				try
				{
					return bool.Parse(str);
				}
				catch (FormatException exception)
				{
					throw new FormatException(ResourceProvider.GetString(StringKeys.ConvertError, str, "Boolean"), exception);
				}
			}
			return base.ConvertFrom(context, culture, value);
		}

		public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
		{
			return destinationType == typeof(string);
		}

		public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
		{
			if (destinationType == null)
			{
				throw new ArgumentNullException("destinationType");
			}
			if (((destinationType == typeof(string)) && (value != null)) && typeof(bool).IsInstanceOfType(value))
			{
				if (culture == null)
				{
					culture = CultureInfo.CurrentCulture;
				}
				return value.ToString();
			}
			return base.ConvertTo(context, culture, value, destinationType);
		}
	}
}
